package com.phonemap.models;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.phonemap.common.Util;

public class Position {

	public static Entity createOrUpdatePosition(String userId, Double latitude,
			Double longitude) {
		Entity user = User.getSingleUser(userId);
		Entity position = new Entity("Position", user.getKey());
		position.setProperty("userId", userId);
		position.setProperty("latitude", latitude);
		position.setProperty("longitude", longitude);
		position.setProperty("positionDate", new Date());

		Util.persistEntity(position);
		return position;
	}

	public static Entity getSinglePosition(String user) {
		Iterable<Entity> results = Util.listEntities("Position", "user", user);
		List<Entity> entity = new ArrayList<Entity>();
		for (Entity e : results)
			if (e != null)
				entity.add(e);
		if (!entity.isEmpty()) {
			return (Entity) entity.remove(0);
		}
		return null;
	}

	public static Iterable<Entity> getAllPositions() {
		Iterable<Entity> entities = Util.listEntities("Position", null, null);
		return entities;
	}
	
	public static Iterable<Entity> getAllPositions(String kind) {
		Iterable<Entity> entities = Util.listEntities(kind, null, null);
		return entities;
	}

	public static Iterable<Entity> getPosition(String user) {
		Iterable<Entity> entities = Util.listEntities("Position", "user", user);
		return entities;
	}

	public static Iterable<Entity> getRelatedPhonePosstions(String phone) {
		Iterable<Entity> userList = User.getAllUsers();
		List<Entity> positionList = new ArrayList<Entity>();
		for (Entity user : userList) {
			Entity e = Util.getMaxEntities("Position", "userId", user
					.getKey().getName(), "positionDate");
			if (e != null) {
				if (phone.equals(e.getProperty("userId").toString())) {
					if (positionList.size() > 0) {
						positionList.add(positionList.get(0));
						positionList.set(0, e);
					} else {
						positionList.add(0, e);
					}
				} else {
					positionList.add(e);
				}

			}
		}
		return positionList;
	}

	public static String deletePosition(String positionKey) {
		Entity entity = getSinglePosition(positionKey);
		if (entity != null) {
			Util.deleteEntity(entity.getKey());
			return ("Position deleted successfully.");
		} else
			return ("Position not found");
	}
	
	/**
	   * Get all the positions for a user
	   * 
	   * @param kind
	   *          : position kind
	   * @param userName
	   *          : user name
	   * @return: all positions of type user
	   */
	  public static Iterable<Entity> getPositionsForUser(String kind, String userName) {
	    Key ancestorKey = KeyFactory.createKey("User", userName);
	    return Util.listChildren("Position", ancestorKey);
	  }
}
